<template>
    <div class="dashboard-container">
        <div style="margin-bottom: 10px;"><el-tag type="danger">标*参数为必填参数，请正确填写否则会影响评估结果</el-tag></div>
        <div style="margin-bottom: 10px;">
            产权人:
            <el-input placeholder="请输入产权人" v-model="temp.propertyOwner" size="mini" style="width: 300px;"></el-input>
            
        </div>
        
        <el-button type="primary" size="mini" style="margin-bottom: 10px;" @click="handleAddLand">新增土地</el-button>
        <!-- 土地表单 -->
        <el-row >
            <div class="item" v-for="(item,index) in temp.lands" :key="index">
                <span style="margin-right: 20px;">土地{{ index+1 }}.</span>
                <el-input placeholder="土地使用证编号" v-model="item.certNo" size="mini" class="buildInput"></el-input>
                <span style="color: red;">*</span>
                <el-input placeholder="土地证载地址" v-model="item.address" size="mini" class="buildInput"></el-input>
                <span style="color: red;">*</span>
                <el-input type="number" placeholder="土地使用面积（㎡）" v-model="item.area" size="mini" class="buildInput" style="width: 150px;"></el-input>
                <el-select v-model="item.useRightType" placeholder="土地使用权类型" class="buildInput" size="mini" style="width: 80px;">
                    <el-option v-for="uItem in useRightList" :label="uItem" :value="uItem" :key="uItem"></el-option>
                </el-select>
                <el-select v-model="item.purpose" placeholder="土地用途" class="buildInput" size="mini" style="width: 80px;">
                    <el-option v-for="pItem in purposeList" :label="pItem" :value="pItem" :key="pItem"></el-option>
                </el-select>
                <el-select v-model="item.standardType" placeholder="标准地" class="buildInput" size="mini" style="width: 100px;">
                    <el-option label="非标准地" value="0"></el-option>
                    <el-option label="标准地" value="1"></el-option>
                </el-select>
                <span style="color: red;" v-if="item.standardType==1">*</span>
                <el-input v-model="item.contractPrice" placeholder="合同总价格(万元)" size="mini" style="width: 120px;" v-if="item.standardType==1"></el-input>
                <span style="color: red;">*</span>
                <el-date-picker
                    size="mini"
                    v-model="item.expireTime"
                    type="date"
                    placeholder="土地终止日期"
                    value-format="timestamp"
                    class="buildInput"
                >
                </el-date-picker>
                <el-button icon="el-icon-delete" type="danger" size="mini" circle @click="handleDeleteLand" v-if="temp.lands.length>1"></el-button>
            </div>
        </el-row>
        
        <el-button type="primary" size="mini" style="margin-bottom: 10px;" @click="handleAddBuild">新增建筑</el-button>
        <!-- 建筑表单 -->
        <el-row v-for="item,index in temp.buildings" :key="index">
            <div class="item">
                <span style="margin-right: 20px;">建筑{{ index+1 }}.</span>
                <el-input placeholder="产权证号" v-model="item.certNo" size="mini" class="buildInput"></el-input>
                <span style="color: red;">*</span>
                <el-input placeholder="地址" v-model="item.address" size="mini" class="buildInput"></el-input>
                <span style="color: red;">*</span>
                <el-select v-model="item.structure" placeholder="结构" class="buildInput" size="mini">
                    <el-option v-for="jitem in jgList" :label="jitem.name+`(${jitem.description})`" :value="jitem.name" :key="jitem.name"></el-option>
                </el-select>
                <span style="color: red;">*</span>
                <el-input placeholder="层高（m）" v-model="item.floorHeight" size="mini" class="buildInput" style="width: 90px;"></el-input>
                <span style="color: red;">*</span>
                <el-input placeholder="建筑年代" v-model="item.year" size="mini" class="buildInput" style="width: 80px;"></el-input>
                <el-input  placeholder="所在层次" v-model="item.currentFloor" size="mini" class="buildInput" style="width: 80px;"></el-input>
                <el-input placeholder="总楼层" v-model="item.totalFloor" size="mini" class="buildInput" style="width: 80px;"></el-input>
                <span style="color: red;">*</span>
                <el-input placeholder="建筑面积（㎡）" v-model="item.area" size="mini" class="buildInput" style="width: 80px;"></el-input>
                <el-button icon="el-icon-delete" type="danger" size="mini" circle @click="handleDeleteBuild" v-if="temp.buildings.length>1"></el-button>
            </div>
        </el-row>

        <!-- 文件上传 -->
        <el-upload
            class="upload-demo"
            :action="OSS_CONFIG.host"
            :on-preview="handlePreview"
            :before-upload="hanldeUpload"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :limit="10"
            :data="uploadData">
            <el-button size="small" type="primary">附件上传（不动产登记证、身份证、营业执照、租赁合同、买卖合同、发票等）</el-button>
            <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress" :show-text="false"></el-progress> <!-- 显示进度条 -->
        </el-upload>

        <el-table :data="this.temp.pictureUrls">
            <el-table-column label="文件地址">
                <template slot-scope="{row}">
                    {{ row }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="{row, $index}">
                    <el-button type="text"><a :href="OSS_BASE_URL+row" target="_blank">下载</a></el-button>
                    <el-button type="text" style="color: red;" @click="handleDeletePic($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="submit">
            <el-button type="primary" @click="handleSelectPoint">选择坐标</el-button>
            <el-button type="primary" @click="handleSubmit" v-if="temp.longitude" v-loading="loading">提交估价</el-button>
            <el-button @click="handleBack">返回</el-button>
        </div>

        <!-- <img 
            style="margin:20px" 
            width="280" height="140" 
            src="https://api.map.baidu.com/staticimage/v2?ak=anyY8CM0veZ5T8PSMhysX9dQLuSHgLvz&mcode=666666&center=116.403874,39.914888&width=300&height=200&zoom=11"
        /> -->

        <!-- 选择坐标弹窗 -->
        <el-dialog 
            top="20px" 
            :visible.sync="dialogVisible" 
            :close-on-click-modal="false"
            @close="dialogVisible=false"
            :title="'当前选择坐标'+(temp.longitude?`:(${temp.longitude},${temp.latitude})`:'')" 
            width="800px" class="point"
        >
            <div style="position: relative;">
                <div style="position: absolute; top: 10px; left: 10px; z-index: 9999;">
                    <el-select size="mini" v-model="cityName" placeholder="请选择城市" style="width: 100px;">
                        <el-option v-for="item in cityList" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                    <el-input placeholder="请输入地址" v-model="address" size="mini" style="width: 300px;margin-right: 5px;"></el-input>
                    <el-button type="primary" size="mini" @click="searchAddress">搜索</el-button>
                </div>
                <div id="baiduMap" style="width: 100%;height: 500px;"></div>
            </div>
            <div class="bottom" style="padding-top: 5px;">
                <el-button type="primary" @click="dialogVisible=false">确认坐标</el-button>
                <el-button @click="dialogVisible=false">取消</el-button>
            </div>
        </el-dialog>

        <!-- 评估结果 -->
        <el-dialog 
            :visible="dialogVisibleResult" 
            title="评估结果" class="point" 
            @close="dialogVisibleResult=false" 
            top="20px" width="800px">
            <div style="margin-bottom: 20px;line-height: 30px;">
                <table border="1" style="border-collapse: collapse;width: 100%;text-align: center;margin-bottom:20px;">
                    <tr>
                        <th colspan="6">建筑物价值明细</th>
                    </tr>
                    <tr>
                        <td>序号</td>
                        <td>不动产证号</td>
                        <td>坐落</td>
                        <td>建筑面积（㎡）</td>
                        <td>单价（元/㎡）</td>
                        <td>评估价值（万元）</td>
                    </tr>
                    <tr v-for="(item,index) in result.items" v-if="item.propertyType<100">
                        <td>{{index+1}}</td>
                        <td>{{ item.certNo }}</td>
                        <td>{{ item.address }}</td>
                        <td>{{ item.area }}</td>
                        <td>{{  Math.round(item.unitPrice) }}</td>
                        <td>{{ (item.totalPrice/10000).toFixed(2) }}</td>
                    </tr>
                    <tr>
                        <td>小计</td>
                        <td></td>
                        <td></td>
                        <td>{{ result.buildingsArea }}</td>
                        <td></td>
                        <td>{{ (result.buildingsPrice/10000).toFixed(2) }}</td>
                    </tr>
                    <tr>
                        <th colspan="6">土地价值明细</th>
                    </tr>
                    <tr>
                        <td>序号</td>
                        <td>不动产证号</td>
                        <td>坐落</td>
                        <td>土地面积（㎡）</td>
                        <td>单价（元/㎡）</td>
                        <td>评估价值（万元）</td>
                    </tr>
                    <tr v-for="(item,index) in result.items" v-if="item.propertyType>100">
                        <td>{{index+1}}</td>
                        <td>{{ item.certNo }}</td>
                        <td>{{ item.address }}</td>
                        <td>{{ item.area }}</td>
                        <td>{{ Math.round(item.unitPrice) }}</td>
                        <td>{{ (item.totalPrice/10000).toFixed(2) }}</td>
                    </tr>
                    <tr>
                        <td>小计</td>
                        <td></td>
                        <td></td>
                        <td>{{ result.landsArea }}</td>
                        <td></td>
                        <td>{{ (result.landsPrice/10000).toFixed(2) }}</td>
                    </tr>
                    <tr>
                        <th colspan="6">不动产合计价值</th>
                    </tr>
                    <tr>
                        <td>建筑物总面积（㎡）</td>
                        <td>{{result.buildingsArea}}</td>
                        <td>土地总面积（㎡）</td>
                        <td>{{result.landsArea}}</td></td>
                        <td>估价总值（万元）</td>
                        <td>{{((result.landsPrice+result.buildingsPrice)/10000).toFixed(2)}}</td>
                    </tr>
                </table>
                <div id="baiduMapCase" style="width: 500px;height: 300px;display: none;"></div>
                <img :src="mapUrl" style="width: 500px;height: 300px;"/>
                <!-- <p v-if="result.reportUrl">
                    评估报告:
                    <a style="margin-left: 10px;">
                        <el-button type="primary" size="mini" @click="handleDown(OSS_BASE_URL+result.reportUrl)">下载报告</el-button>
                    </a>
                </p> -->
            </div>
            <div>
                <el-button type="primary" @click="dialogVisibleResult=false">关闭结果</el-button>
                <el-button @click="handleBack">返回首页</el-button>
                <el-button @click="getReport">下载报告</el-button>
            </div>
        </el-dialog>

        

        
    </div>
  </template>
  
<script>
import { enumInfo } from '@/api/enum'
import { commonGetCityList, commonGetUploadFilePolicy } from '@/api/common'
import { enquiryAutoIndustry1, enquiryAutoIndustry2 } from '@/api/enquiry'
import { OSS_BASE_URL, useRightList } from '@/utils/common'
import { getDistance, generateUUID } from '@/utils/tools'
import html2canvas from 'html2canvas'
import axios from 'axios'
import moment from 'moment'
import Compressor from 'compressorjs';
 

  const buildItem = { certNo: '',address:'', structure: '', floorHeight: '',year: '', currentFloor: '', totalFloor: '', area: ''};
  const landsItem = { certNo: '',address:'', area: '', useRightType: '出让', purpose: '工业', expireTime: '', standardType: '0'};
  let map, map2;
  let marker;

  export default {
    name: 'EnquiryAdd',
    data() {
      return {
        useRightList,
        purposeList: ['工业', '商业', '住宅'],
        jgList: [],
        temp: {
            propertyOwner: '',
            longitude: '',
            latitude: '',
            buildings  : [
                { certNo: '',address:'', structure: '', floorHeight: '',year: '', currentFloor: '', totalFloor: '', area: ''}
            ],
            lands: [
                { certNo: '',address:'', area: '', useRightType: '出让', purpose: '工业', expireTime: '', standardType: '0'}
            ],
            pictureUrls: []
        },
        dialogVisible: false,
        address: '',
        cityName: '杭州市',
        cityList: [],
        dialogVisibleResult: false,
        OSS_BASE_URL,
        result: {
            id: "",
            reportUrl: '',
            items: [],
            buildingsArea: '',
            buildingsPrice: '',
            landsArea: '',
            landsPrice: ''
        },
        loading: false,
        OSS_CONFIG: {
            accessid: '',
            dir: '',
            expire: '',
            host: '',
            policy: '',
            signature: ''
        },
        uploadData: {},
        fileList: [],
        mapUrl: '',
        uploadProgress: 0,
        
      }
      
    },
 
    async mounted(){
        this.getOssConfig();
        let data = await commonGetCityList({ geoLevel: 2, provinceId: 11 });
        this.cityList = data.map(item=>item.name);
        this.getEnumFindBest();
    },
    methods: {
        
        //删除钩子
        handleRemove(file){
            this.temp.pictureUrls = this.temp.pictureUrls.filter(item=>{
                return item.indexOf(file.uid)==-1
            })
        },

        //删除该图片
        handleDeletePic(index){
            this.temp.pictureUrls.splice(index, 1)
        },

        uploadFile(file) {
            const formData = new FormData();
            let fileName = generateUUID() + '.' + file.name.split('.')[1]
            formData.append('name', fileName);
            formData.append('key', this.OSS_CONFIG.dir + fileName);
            formData.append('policy', this.uploadData.policy);
            formData.append('OSSAccessKeyId', this.uploadData.OSSAccessKeyId);
            formData.append('success_action_status', this.uploadData.success_action_status);
            formData.append('signature', this.uploadData.signature);
            formData.append('file', file);
            // 发送POST请求到服务器，此处可以使用axios等HTTP客户端库
            axios.post(this.OSS_CONFIG.host, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
                // onUploadProgress: progressEvent => {
                //     console.log(progressEvent, 111)
                //     // 更新上传进度条的值，这里通常是百分比形式
                //     this.uploadProgress = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total));
                //     console.log(progressEvent, 222)
                // }
            }).then(response => {
                this.uploadProgress = 0;
                // this.handleSuccess(response); // 处理上传成功后的逻辑
                
                this.temp.pictureUrls.push(this.OSS_CONFIG.dir + fileName)
            }).catch(error => {
                console.log(error, "失败了")
                // this.handleError(error); // 处理上传失败后的逻辑
            });
        },
        //图片上传前，签名处理
        hanldeUpload(file){
            //做图片压缩处理
            const reader = new FileReader();
            reader.readAsDataURL(file); // 读取文件内容
            reader.onload = (e) => {
                new Compressor(file, {
                    quality: 1, // 压缩质量，范围0.1到1.0之间，1为原图大小，0.6为中等压缩比，可根据需要调整
                    maxWidth: 1920,
                    maxHeight: 1080,
                    convertSize: 2048,
                    success: (compressedResult) => {
                        // 使用压缩后的图片进行上传操作，此处可以直接使用compressedResult上传或者转换为FormData上传
                        this.uploadFile(compressedResult); // 调用上传方法
                    },
                    error(err) {
                        console.error('Compression failed', err.message);
                    },
                    // 其他配置...
                });
            };
            return false; // 阻止自动上传，因为我们手动处理了上传逻辑
            // if(file.size>1024*1024*2){
            //     this.$message.error('文件不得大于2M')
            //     return false
            // }
            //判断一下签名有没有请求到
            // if(moment(this.OSS_CONFIG.expire)<moment()||this.OSS_CONFIG.expire==''){
            //     let data = await commonGetUploadFilePolicy();
            //     this.OSS_CONFIG = data;
            //     this.uploadData = {
            //         policy: data.policy,
            //         OSSAccessKeyId: data.accessid,
            //         success_action_status: '200',
            //         signature: data.signature,
            //         key: data.dir,
            //         name: ''
            //     }
            // }
            
            // let fileName = file.uid + '.' + file.name.split('.')[1]
            // this.uploadData.name = fileName
            // this.uploadData.key = this.OSS_CONFIG.dir + fileName
        },
        //点击文件列表
        handlePreview(file){
            
        },
        //文件上传成功
        handleAvatarSuccess(){
            console.log('上传成功')
            this.temp.pictureUrls.push(this.uploadData.key)
        },
        //文件地址转化为blob对象
        dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        },
        //获取报告
        async getReport(){
            this.handleDown(OSS_BASE_URL+this.result.reportUrl);
        },

        //获取Oss详情
        async getOssConfig(){
            let data = await commonGetUploadFilePolicy();
            this.OSS_CONFIG = data;
            this.uploadData = {
                policy: data.policy,
                OSSAccessKeyId: data.accessid,
                success_action_status: '200',
                signature: data.signature,
                key: data.dir,
                name: ''
            }
        },
        //设置缩放级别
        setZoom(points){  
            if(points.length>1){  
                var maxLng = points[0].lng;  
                var minLng = points[0].lng;  
                var maxLat = points[0].lat;  
                var minLat = points[0].lat;  
                var res;  
                for (var i = points.length - 1; i >= 0; i--) {  
                    res = points[i];  
                    if(res.lng > maxLng) maxLng =res.lng;  
                    if(res.lng < minLng) minLng =res.lng;  
                    if(res.lat > maxLat) maxLat =res.lat;  
                    if(res.lat < minLat) minLat =res.lat;  
                };  
                var cenLng =(parseFloat(maxLng)+parseFloat(minLng))/2;  
                var cenLat = (parseFloat(maxLat)+parseFloat(minLat))/2;  
                var zoom = this.getZoom(maxLng, minLng, maxLat, minLat);  
                // map2.centerAndZoom(new BMapGL.Point(cenLng,cenLat), zoom);    
                return { cenLng, cenLat, zoom }
            }else if(points.length==1){
                return { cenLng: points[0].lng, cenLat: points[0].lat, zoom: 10 } 
            }else{  
                //没有坐标，显示全中国  
                // map2.centerAndZoom(new BMapGL.Point(103.388611,35.563611), 5);   
                return { cenLng: 103.388611, cenLat: 35.563611, zoom: 5 } 
            }   
        },
        //缩放级别函数
        getZoom (maxLng, minLng, maxLat, minLat) {  
            var zoom = ["50","100","200","500","1000","2000","5000","10000","20000","25000","50000","100000","200000","500000","1000000","2000000"]//级别18到3。  
            var pointA = new BMapGL.Point(maxLng,maxLat);  // 创建点坐标A  
            var pointB = new BMapGL.Point(minLng,minLat);  // 创建点坐标B  
            var distance = map2.getDistance(pointA,pointB).toFixed(1);  //获取两点距离,保留小数点后两位  
            for (var i = 0,zoomLen = zoom.length; i < zoomLen; i++) {  
                if(zoom[i] - distance > 0){  
                    return 18-i+2;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。  
                }  
            };  
        }, 
        //初始化案例地图
        async initMapCase(casePonit, caseOtherList, points){
            map2 = new BMapGL.Map("baiduMapCase");
            //生成静态地图
            let baseUrl = 'https://api.map.baidu.com/staticimage/v2?ak=anyY8CM0veZ5T8PSMhysX9dQLuSHgLvz&width=500&height=300'
            
            // 动态计算地图的中心点及缩放级别
            let { cenLng, cenLat, zoom } = this.setZoom(points);
            //中心点及缩放
            let center = `&center=${cenLng},${cenLat}&zoom=${zoom}`
            // 标注
            let markers = `&markers=`
            
            let labels ='&labels='
            let labelStyles = `&labelStyles=估价对象,1,20,0x990099,0xff00,1`;
            let paths = `&paths=`;
            points.forEach((item, index)=>{
                if(index>0){
                    // 获取距离
                    let distance = getDistance(points[0].lng, points[0].lat, item.lng, item.lat)
                    labelStyles += `|${distance}km,1,20,0x990099,0xff00,1`
                    paths+=`${points[0].lng},${points[0].lat};${item.lng},${item.lat}|`
                }
                // 画样式
                labels += `${item.lng},${item.lat}|`
                markers += `${item.lng},${item.lat}|`
            })
            console.log(labels, labelStyles, paths)
            let pathStyles = `&pathStyles=0xc73257,1,1`
            //地图的地址
            this.mapUrl = baseUrl+center+markers+labels+labelStyles+paths+pathStyles;
            // 做地址的转码
            let mapUrl = encodeURIComponent(baseUrl+center+markers+labels+labelStyles+paths+pathStyles);
            let data = await enquiryAutoIndustry2({ id: this.result.id, mapUrl })
            this.result.reportUrl = data.reportUrl;
            
        },
        setLabel(point, content){
            var label = new BMapGL.Label(content, {       // 创建文本标注
                position: point,                          // 设置标注的地理位置
                offset: new BMapGL.Size(10, 20)           // 设置标注的偏移量
            })  
            map2.addOverlay(label);                        // 将标注添加到地图中
        },
        // 下载
        handleDown(url) {
            return fetch(url).then(response=>{
                if(!response.ok){
                    throw new Error('network not ok')
                }
                return response.blob();
            }).then(blob=>{
                const url = window.URL.createObjectURL(blob);
                const elink = document.createElement('a')
                elink.style.display = 'none'
                elink.href = url;
                elink.download = this.temp.propertyOwner + '所属位于' + this.temp.lands[0].address + '工业不动产询价单.docx'
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)// 释放对象
                document.body.removeChild(elink)// 移除元素

            }).catch(error=>{
                console.log('error', error)
            })
        },

        //根据地址搜索经纬度
        searchAddress(){
            let that = this;
            var options = {
                onSearchComplete: function(results){
                    // 判断状态是否正确
                    if (local.getStatus() == BMAP_STATUS_SUCCESS){
                        that.temp.latitude = results.getPoi(0).point.lat
                        that.temp.longitude = results.getPoi(0).point.lng
                        var point = new BMapGL.Point(that.temp.longitude, that.temp.latitude); // 地图中心点坐标
                        marker = new BMapGL.Marker(point);
                        map.addOverlay(marker);
                        map.centerAndZoom(point, 15); // 初始化地图，设置中心点坐标和地图级别
                    }
                }
            };
            var local = new BMapGL.LocalSearch(map, options);
            local.search(this.cityName + this.address);
        },
        //选择坐标
        handleSelectPoint(){
            if(!this.temp.lands[0].address){
                this.$message.error({ message: '请填写土地证地址'})
                return;
            }
            this.address = this.temp.lands[0].address;
            this.dialogVisible = true;
            setTimeout(()=>{
                this.initMap();
            },100)
            
        },
        //初始化百度地图
        initMap(){
            map = new BMapGL.Map("baiduMap");
            var point = new BMapGL.Point(120.264267, 30.1841); // 地图中心点坐标
            map.centerAndZoom(point, 15); // 初始化地图，设置中心点坐标和地图级别
            // 打开地图缩放
            map.enableScrollWheelZoom(true);
            //搜索地址
            this.searchAddress();

            //监听地图点击事件
            map.addEventListener('click', (e)=>{
                map.removeOverlay(marker);
                let { lng, lat} = e.latlng;
                this.temp.longitude = lng;
                this.temp.latitude = lat;
                marker = new BMapGL.Marker(e.latlng);        // 创建标注   
                map.addOverlay(marker);
            })
        },
        //获取房产结构枚举类型
        async getEnumFindBest(){
            let data = await enumInfo({ id: 22})
            this.jgList = data.items.map(item=>{
                let str = '';
                item.values.forEach(vItem=>{
                    str= str + vItem.enumTitleName + ':' + vItem.value + ';'
                })
                item.str = str;
                return item;
            })
        },
        //提交表单
        async handleSubmit(){
            let temp = JSON.parse(JSON.stringify(this.temp));
            temp.buildings = temp.buildings.filter(item=>item.address)
            let error = '';
            temp.lands.forEach((item,index)=>{
                if(!item.address)return error=`土地${index+1}地址必填`
                if(!item.area)return error=`土地${index+1}使用面积必填`
                if(!item.expireTime)return error=`土地${index+1}终止日期必填`
                if(item.standardType==1&&!item.contractPrice)return error=`土地${index+1}为标准地需要填写合同总价`
            })
            temp.buildings.forEach((item,index)=>{
                if(!item.structure)return error=`建筑${index+1}结构必选`
                if(!item.floorHeight)return error=`建筑${index+1}层高必填`
                if(!item.year)return error=`建筑${index+1}年代必填`
                if(!item.area)return error=`建筑${index+1}面积必填`
            })
            if(error){
                this.$message.error({ message: error })
                return;
            }

            this.loading = true;
            // 必填参数土地： 土地证载地址address 土地使用面积（㎡）area  土地终止日期expireTime
            // 必填建筑： 地址address  结构structure  平均层高（m）floorHeight 建筑年代year 建筑面积（㎡）area
            
            let data = await enquiryAutoIndustry1(temp)
            this.loading = false;
            let { reportUrl, items, buildingsArea, buildingsPrice, landsArea, landsPrice, relatedTargets, id } = data;
            // this.result.reportUrl = reportUrl; //改到第二阶段了
            this.result.id = id;
            this.result.items = items;
            this.result.buildingsArea = buildingsArea;
            this.result.landsArea = landsArea;
            this.result.buildingsPrice = buildingsPrice;
            this.result.landsPrice = landsPrice;
            this.result.relatedTargets = relatedTargets?relatedTargets:[]; // 附近3个案例 longitude、latitude、name
    
            // items下参数   totalPrice unitPrice propertyType 102是土地 2是建筑
            this.dialogVisibleResult = true;
            
            setTimeout(()=>{
                //创建初始化地图
                var casePonit = new BMapGL.Point(this.temp.longitude, this.temp.latitude); // 地图中心点坐标
                let points =[];
                points.push({  lng: this.temp.longitude, lat: this.temp.latitude});
                this.result.relatedTargets.forEach(item=>{
                    points.push({  lng: item.longitude, lat: item.latitude});
                })
                this.initMapCase(casePonit, this.result.relatedTarget, points);
            },100)
            
        },
        //返回
        handleBack(){
            this.$router.history.push({ path: '/home/index' })
        },
        //点击添加土地
        handleAddLand(){
            this.temp.lands.push(JSON.parse(JSON.stringify(landsItem)));
        },
         //点击删除土地
        handleDeleteLand(index){
            this.temp.lands.splice(index, 1)
        },
        //点击添加建筑
        handleAddBuild(){
            this.temp.buildings.push(JSON.parse(JSON.stringify(buildItem)));
        },
         //点击删除土地
        handleDeleteBuild(index){
            this.temp.buildings.splice(index, 1)
        }

        
    }
  }
  </script>

<style>
.point .el-dialog__body{
    padding-top: 0;
}
</style>
  
<style lang="scss" scoped>

.dashboard {
  &-container {
    margin: 15px;
    position: relative;
    .submit{
        padding-top: 20px;
    }
    .item{
        // margin-bottom: 5px;
    }
    .buildInput{
        width: 150px;
        margin-right: 5px;
        margin-bottom: 10px;
    }
  }
}
</style>
  